package at.jku.ssw.fortress.ui;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;


public class MacroManager {

	public static class Macro {
		public char unicode;
		public String name;
		public String category;

		public Macro(String category, String name, char unicode) {
			super();
			this.name = name;
			this.unicode = unicode;
		}
	}

	private Map<String, Macro> representations;
	private Map<String, List<Macro>> categories;

	public MacroManager() {
		categories = new HashMap<String, List<Macro>>();
		representations = new HashMap<String, Macro>();
	}
	
	public void loadMacros(String file, String category) {
		try {
			Bundle plugin = Platform.getBundle(FortressPlugin.PLUGIN_ID);
			URL url = FileLocator.find(plugin, Path.fromOSString(file), null);
			BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream()));

			List<Macro> macros = new ArrayList<Macro>();
			categories.put(category, macros);
			
			String line;
			while ((line = r.readLine()) != null) {
				if(line.replace(" ", "").length() == 0 || line.charAt(0) == '#') continue;
				String[] parts = line.split(";");
				String code = parts[0];
				char unicode = (char) Integer.parseInt(code, 16);
				String[] asciiNames = parts[1].split(" ");
				Macro m = null;
				for(String name : asciiNames) {
					m = representations.get(name);
					if(m == null) {
						m = new Macro(category, name, unicode);
						macros.add(m);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Macro[] getMacros(String category) {
		List<Macro> macros = categories.get(category);
		if(macros != null) {
			return macros.toArray(new Macro[0]);
		}
		return new Macro[0];
	}


}
